package com.gyh.system.sys.service;

import java.util.Date;

import org.springframework.beans.factory.InitializingBean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.gyh.system.common.utils.Global;
import com.gyh.system.common.utils.R;
import com.gyh.system.sys.dao.UserTokenDao;
import com.gyh.system.sys.entity.UserToken;
import com.gyh.system.sys.utils.TokenGenerator;

/**
* @author 作者 gyh:
* @version 创建时间：2018年1月13日 上午12:53:40
* 
*/
@Service
public class ShiroService implements InitializingBean {

	@Autowired
	private UserTokenDao userTokendao;
	
	public R createToken(Long userId) {
		//生成一个token
		String token = TokenGenerator.generateValue();
		
		//当前时间
		Date now = new Date();
		//过期时间
		Date expireTime = new Date(now.getTime() + Global.TOKEN_EXPIRE * 1000);
		
		//判断是否生成过token
		UserToken tokenEntity = userTokendao.get(userId);
		if(tokenEntity == null){
			tokenEntity = new UserToken();
			tokenEntity.setUserId(userId);
			tokenEntity.setToken(token);
			tokenEntity.setUpdateTime(now);
			tokenEntity.setExpireTime(expireTime);
			userTokendao.insert(tokenEntity);
		}else{
			tokenEntity.setToken(token);
			tokenEntity.setUpdateTime(now);
			tokenEntity.setExpireTime(expireTime);
			//更新token
			userTokendao.update(tokenEntity);
			//ShiroUtils.removeSysUserTokenEntity(token);
		}
		R r = R.ok().put("token", token).put("expire", Global.TOKEN_EXPIRE);
		return r;
	}
	
	
	@Override
	public void afterPropertiesSet() throws Exception {
		// TODO Auto-generated method stub
		
	}


}
